package TestNet;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class ThreadRecieve {

}

class TRecieve implements Runnable {
    DatagramSocket RecieveSocket = null;
    DatagramPacket RecievePacket = null;
    InetAddress ip = null;
    String name;
    private int port;

    public TRecieve (String name, InetAddress ip, int port) {
        this.port = port;
        this.ip = ip;
        this.name = name;
        try {
            RecieveSocket = new DatagramSocket (port);
            byte[] bytes = new byte[1024];
            RecievePacket = new DatagramPacket (bytes, 0, bytes.length, ip, port);
        } catch (SocketException e) {
            e.printStackTrace ();
        }
    }

    @Override
    public void run () {
        try {
            while (true) {
                RecieveSocket.receive (RecievePacket);
                byte[] data = RecievePacket.getData ();
                System.out.println (name + ":" + new String (data));
                String str = new String (data, 0, RecievePacket.getLength ());
                if (str.equals ("bye")) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace ();
        } finally {
            RecieveSocket.close ();
        }
    }
}
